var returnAnalysisRst = null; // global json object storing the ltp server return value

$(document).ready(function () {

    //-----main view-----
    var analysisBtn, // the button for active analysis
        readySentView = null, // function to set the sent view
        readyXmlView = null,
        readyParaView = null,
        maskObj = document.getElementById("mask"),
        manualObj = document.getElementById("usingManual"),
        loadingObj = document.getElementById("loadingTag"),
        loadingOriHtml = loadingObj.innerHTML,
        setLoadingPos = null, // function to set loading tag position
        analysisBtn = $("#analysis");

    analysis = function () {
        var requestArgs = [],
            postData;

        requestArgs["pattern"] = "all";
        requestArgs["format"] = "json";
        requestArgs["text"] = encodeURI($("#inputText").val());
        postData = (function () {
            var tmpStrArray = [];
            for (key in requestArgs) {
                tmpStrArray.push([key, requestArgs[key]].join("="));
            }
            return tmpStrArray.join("&");
        })();

        getDataFun()

        function getDataFun() {
            var paragraphs = $("#inputText").val();
            var paragraphArr = [paragraphs];
            // var paragraphArr = paragraphs.split('\n')
            //                   .filter(function (item) { return item })
            //                   .map(function (item) {
            //                     return item.replace(/。|……|？|！|；/g, "$&\n").split('\n')
            //                           .filter(function (item) { return item })
            //                   })
            var sentenceArr = [].concat.apply([], paragraphArr)

            if (sentenceArr.length === 0) return;

            displayLoadingPage();

            (function getData(semgraphparserErr, times) {
                if (times > 1) return

                var engine = $('input[name="engine"]:checked').val();

                var ajaxArr = [];
                sentenceArr.forEach(function (item) {
                    ajaxArr.push(
                        // $.ajax({url: "//192.168.1.132/grammarAnalyze", async: false, data: "s=" + item + "&e=" + engine + "&f=xml&t=all", type: 'GET'})
                        $.ajax({url: "/api/grammarAnalyze", async: false, data: "s=" + item + "&e=" + engine + "&f=xml&t=all", type: 'GET', headers: {'token': sessionStorage.token}})
                    )
                });
                $.when.apply(this, ajaxArr).then(function () {
                    var semgraphparserErr = false
                    if (ajaxArr.length === 1) {
                        if (arguments[0] === '{}') semgraphparserErr = true
                        resArr = [arguments[0]]
                    } else {
                        var resArr = [].map.call(arguments, function (item) {
                            if (item[0] === '{}') semgraphparserErr = true
                            return item[0]
                        })
                    }

                    if (semgraphparserErr) {
                        setTimeout(function functionName() {
                            getData(semgraphparserErr, times++)
                        }, 1000)
                        return;
                    }

                    try {
                        // var returnVal = generateData(paragraphArr, resArr)
                        // console.log(JSON.stringify(returnVal))
                        var localXML = parseString2XMLDOM(resArr[0].xml);
                        var localJson = LTPRstParseXMLDOM2JSON(localXML);
                        returnAnalysisRst = localJson;
                        //sent view update
                        readySentView();
                        //xml view update
                        readyXmlView(localJson);
                        labelExplanationPanel._responseBtnAppear();
                    } catch (e) {
                        ajaxFailFun({responseText: e.message}, '解析出错')
                    }
                }, ajaxFailFun)
            })(false, 0)
        }

        function generateData(paragraphArr, resWordsArr) {
            var data = []
            var k = 0
            paragraphArr.forEach(function (item, i) {
                if (!data[i]) data[i] = []
                item.forEach(function (item, j) {
                    data[i][j] = LTPRstParseXMLDOM2JSON(parseString2XMLDOM(resWordsArr[k].xml));
                    k++
                })
            })

            /*for (var i = 0; i < data.length; i++) {
              for (var j = 0; j < data[i].length; j++) {
                var tmpArr = []
                for (var k = 0; k < data[i][j].length; k++) {
                  var word = data[i][j][k]
                  var tmp = {
                    id: word.id,
                    cont: word.cont,
                    pos: word.pos,
                    ne: word.ne,
                    parent: word.parent,
                    relate: word.relate,
                    semparent: word.semparent,
                    semrelate: word.semrelate,
                    arg: word.arg || [],
                    sem: word.sem || []
                  }
                  tmpArr.push(tmp)
                }
                data[i][j] = tmpArr
              }
            }*/

            return data
        }

        function ajaxFailFun(errorInfo, errorType) {
            console.log(errorInfo);
            loadingObj.innerHTML = ['<p class="text-error">',
                '发送分析请求失败！请点击<code>分析</code>重试.',
                '</p>'].join('');
            loadingObj.innerHTML += '<p>' + errorType;
            loadingObj.innerHTML += errorInfo.responseText;
        }

        function displayLoadingPage() {
            maskObj.style.display = "block";
            analysisPanel.style.display = "none";
            manualObj.style.display = "none";
            loadingObj.innerHTML = loadingOriHtml;
            loadingObj.style.display = "block";
            setLoadingPos();
            this.blur(); // make the button blur . focusing status looks not-beautiful
        }

        return false;
    }

    readySentView = function () {
        initDom(DRAW_PARENT_ID, returnAnalysisRst); //init the sent view
        //update UI ! it is necessary to update it before drawing the canvas
        maskObj.style.display = "none";
        analysisPanel.style.display = "block";
        //active the sent view
        $("#sent-tab").tab('show');
        //! `lastOpendEle` is a global variable ! For switch animating !
        //~ first , make the first text item be the lastOpenedEle to init the draw state
        lastOpenedEle = document.getElementById(DRAW_PARENT_ID).getElementsByTagName("DIV")[0];
        //! draw canvas for first line .
        drawCanvas(lastOpenedEle);
        //! set label explanation panel content . according to current demo draw data .
        updateLabelExplanationPanelContent();
        //! important ! subsequent switching animate rely on this setting
        lastOpenedEle.parentNode.getElementsByTagName("CANVAS")[0].parentNode.style.height = CANVAS_HEIGHT + "px";
    }

    readyParaView = function () {
        // has build a bad function ! - -
        selectParaPartToDrawByValue($("input[name=paraDisItem]:checked").val());
    }
    readyXmlView = function (returnJsonObj) {
        var xmlDOM = LTPRstParseJSON2XMLDOM(returnJsonObj),
            str = parseXMLDOM2String(xmlDOM),
            formatedStr = formatDOMStrForDisplay(str);
        $("#xml_area").val(formatedStr);
    }

    setLoadingPos = function () {
        var parentNode = maskObj,
            pWidth = parentNode.offsetWidth,
            left;
        if (pWidth != 0) {
            left = (pWidth - loadingObj.offsetWidth) / 2;
            loadingObj.style.left = left + "px";
        }
    }
    //---------------Event Bind----------------
    analysisBtn.bind("click", analysis);
    $("#viewTab a").click(function (e) {
        e.preventDefault();
        $(this).tab('show');
        var targetId = e.target.getAttribute("id");
        //! If change to other tab except for sent-tab , we close the panel to restore the main content .
        if (targetId != "sent-tab") {
            labelExplanationPanel.closePanel();
            labelExplanationPanel._responseBtnBoxHide();
        } else {
            labelExplanationPanel._responseBtnBoxAppear();
        }
        if (targetId == "para-tab") selectParaPartToDrawByValue($("input[name=paraDisItem]:checked").val());
    });

    $("#load-local-xml-btn").bind("click", function (e) {
        var localXML = parseString2XMLDOM($("#xml_area").val()),
            localJson = LTPRstParseXMLDOM2JSON(localXML);
        if (localJson != [] && localJson != undefined) {
            returnAnalysisRst = localJson;
            readySentView();
        }
        return false;
    })
    $(window).bind("resize", function (e) {
        if (demo != null) {
            demo.move(0, 0);
        }
        setLoadingPos();
    });
    //----------------First Call--------------------------
    initNerIntro();
    // $("#inputText").val("判美海军埃塞克斯号两栖攻击舰位钓鱼岛以东海域活动。");
});
